package win.larryzeal.redisdemo.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;

/**
 * Created by 张少昆 on 2017/1/5.
 */
public class RedisConfig {
	@Value( "${redis.maxIdle}" )
	private int maxIdle;
	@Value( "${redis.minEvictableIdleTimeMillis}" )
	private long minEvictableIdleTimeMillis;
	@Value( "${redis.numTestsPerEvictionRun}" )
	private int numTestsPerEvictionRun;
	@Value( "${redis.timeBetweenEvictionRunsMillis}" )
	private long timeBetweenEvictionRunsMillis;

	@Value( "${redis.hostName}" )
	private String hostName;
	@Value( "${redis.port}" )
	private int port;
	@Value( "${redis.timeout}" )
	private int timeout;
	@Value( "${redis.usePool}" )
	private boolean usePool;

	/**
	 * Config for jedisPool
	 *
	 * @return
	 */
	@Bean
	public JedisPoolConfig jedisPoolConfig(){
		JedisPoolConfig config = new JedisPoolConfig();
		config.setMaxIdle(maxIdle);
		config.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
		config.setNumTestsPerEvictionRun(numTestsPerEvictionRun);
		config.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
		return config;
	}

	/**
	 * 连接工厂!
	 *
	 * @return
	 */
	@Bean
	public JedisConnectionFactory jedisConnectionFactory(){
		JedisConnectionFactory factory = new JedisConnectionFactory();
		factory.setPoolConfig(jedisPoolConfig());
		factory.setHostName(hostName);
		factory.setPort(port);
		factory.setTimeout(timeout);
		factory.setUsePool(usePool);
		return factory;
	}

	@Bean
	public RedisTemplate redisTemplate(){
		RedisTemplate redisTemplate = new RedisTemplate();
		redisTemplate.setConnectionFactory(jedisConnectionFactory());
		redisTemplate.setDefaultSerializer(new StringRedisSerializer()); //不是默认的吗
		redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());//不是默认的吗
		return redisTemplate;
	}
}
